#!/bin/sh
# set -x
HERE=$(cd $(dirname "$0"); pwd)

source /Users/haicheng/code/github/shell-tool/func.lib.sh

DATA_SOURCE="$HERE/data/redis-cluster"
LIB_SOURCE="$HERE/services"

# xecho "分片前的清理工作" 
sudo docker-compose stop

xecho "--清理工作"
for port in `seq 7001 7006`; do \
  rm -rf $DATA_SOURCE/${port}; \
done

local_ip=""
getIpAddr

xecho "获取ip（mac本地） ${local_ip}" 
export LOCAL_IP=${local_ip} && envsubst < $HERE/env.sample > $HERE/.env

xecho "开始创建目录" 
for port in `seq 7001 7006`; do \
  export PORT=${port} \
  && mkdir -p $DATA_SOURCE/${port}/conf \
  && touch $DATA_SOURCE/${port}/conf/redis.conf \
  && envsubst < $LIB_SOURCE/redis-cluster/redis-cluster.tmpl > $DATA_SOURCE/${port}/conf/redis.conf \
  && mkdir -p $DATA_SOURCE/${port}/data ;\
done

for port in `seq 7001 7006`; do \
  rm -rf $DATA_SOURCE/${port}/data/appendonly.aof; \
  rm -rf $DATA_SOURCE/${port}/data/nodes.conf; \
  rm -rf $DATA_SOURCE/${port}/data/redis.log; \
  rm -rf $DATA_SOURCE/${port}/data/dump.rdb; \
done

xecho "开始启动docker" 
sudo docker-compose up -d

# xecho "开始手动redis cluster切片" 

# xecho "jedis没有做分片，暂时关闭这里，正常应该分片。。" 
# docker exec -it redis7001 redis-cli -p 7001 --cluster create ${local_ip}:7001 \
# ${local_ip}:7002 ${local_ip}:7003 ${local_ip}:7004 ${local_ip}:7005 ${local_ip}:7006 --cluster-replicas 1

xecho "完成" 
xecho "使用时替换集群配置为\"localhost:7001\" 即可。" 